package com.cloudptt.wp.ui.message.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cloudptt.api.comm.FileOperation;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.MsgOperator;
import com.cloudptt.api.product.res.Resource;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.message.MessagesStatusActivity;
import com.cloudptt.wp.ui.message.SessionActivity;
import com.cloudptt.wp.ui.message.component.AudioPlayer;
import com.mcptt.config.body.info.mcdata.FileMataInfo;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.SessionInfo;
import com.squareup.picasso.Picasso;

import java.util.List;


public class SessionAdapter extends BaseAdapter
{

	private Context ctx = null;
	private AddrInfo curAddrInfo = null;
	private List<SessionInfo> list = null;
	//	private ProgressDialog dlg;
	private IDownload download = null;
	private boolean isFunc = false;
	public SessionAdapter(Context ctx,AddrInfo curUserInfo,List<SessionInfo> list,IDownload download,boolean isFunc)
	{
		this.ctx = ctx;
		this.curAddrInfo = curUserInfo;
		this.list = list;
		this.download = download;
		this.isFunc = isFunc;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return this.list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder viewHolder;

		SessionInfo info = list.get(position);
		Log.debug(getClass(), "getView info = " + info);
		int direction = info.getDirection();
		int status = info.getStatus();
		if (status != SessionInfo.Status_SDS_READ
				&& SessionInfo.Direction_Type_Receive == direction)
		{
			int dispositionReqType = info.getDispositionReqType();
			if((dispositionReqType & SessionInfo.READ) > 0)
			{
				SysApplication app = ((SysApplication) ctx.getApplicationContext());
				Product product = app.getProduct();
				MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
				operator.sendNtfMessage(info,SessionInfo.Status_SDS_READ);
			}
		}
		if (convertView == null)
		{
			LayoutInflater inflater = LayoutInflater.from(ctx);
			if (SessionInfo.Direction_Type_Send == direction)
				convertView = inflater.inflate(R.layout.chatting_item_msg_send, null);
			else
				convertView = inflater.inflate(R.layout.chatting_item_msg_recv, null);

			viewHolder = new ViewHolder();
			viewHolder.imgView = (ImageView) convertView.findViewById(R.id.iv_userhead);
			viewHolder.tvUserName = (TextView) convertView
					.findViewById(R.id.tv_username);
			viewHolder.tvSendTime = (TextView) convertView
					.findViewById(R.id.tv_sendtime);
//			viewHolder.funcTitleTv = (TextView) convertView
//					.findViewById(R.id.tv_func_title);
//			viewHolder.contentLy = (FrameLayout) convertView
//					.findViewById(R.id.contentLy);
			viewHolder.textTv = (TextView) convertView
					.findViewById(R.id.textTv);
			viewHolder.imageIv = (ImageView) convertView
					.findViewById(R.id.imageIv);
			viewHolder.voiceIv = (ImageView) convertView
					.findViewById(R.id.voiceIv);

			viewHolder.fileLy = (LinearLayout) convertView
					.findViewById(R.id.fileLy);
			viewHolder.fileNameTv = (TextView) convertView
					.findViewById(R.id.fileNameTv);
			viewHolder.fileSizeTv = (TextView) convertView
					.findViewById(R.id.fileSizeTv);


			viewHolder.statusTv = (TextView) convertView
					.findViewById(R.id.stateTv);
			convertView.setTag(viewHolder);
		}
		else
		{
			viewHolder = (ViewHolder) convertView.getTag();
		}
		if (SessionInfo.Direction_Type_Send == direction)
		{
			String val = Resource.getMcdtataStatusString(info.isFdMsg(),status);
			Log.debug(getClass(), "getView status = " + status + " val = " + val);
			if(!isFunc && info.isShowStatus()) {
				viewHolder.statusTv.setText(val);
				viewHolder.statusTv.setVisibility(View.VISIBLE);
			}
			else
			{
				viewHolder.statusTv.setVisibility(View.INVISIBLE);
			}
			if(!info.isOtoMsg())
			{
				viewHolder.statusTv.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// 在这里，position就是点击的控件所在的行
						// 你可以在这里处理点击事件，例如弹出Toast或者跳转到另一个Activity
						doViewClick(R.id.stateTv,position);
					}
				});
			}
		}
		if(curAddrInfo != null
				&& this.curAddrInfo.isGroupType())
		{
			viewHolder.tvUserName.setVisibility(View.VISIBLE);
			String name = info.getSenderAddrInfo().getDscp();
			viewHolder.tvUserName.setText(name);
		}
		else
		{
			viewHolder.tvUserName.setVisibility(View.GONE);
		}
//		if(info.isFuncMsg())
//		{
//			String peerNum = info.getPeerAddrInfo().getAddrId();
//			String sendernum = info.getSenderAddrInfo().getAddrId();
//			String resultStr = ctx.getString(R.string.func_msg_title, peerNum,sendernum);
//			Log.debug(this.getClass(),"onQueryResult resultStr = " + resultStr);
//			viewHolder.funcTitleTv.setText(resultStr);
//			viewHolder.funcTitleTv.setVisibility(View.VISIBLE);
//		}
//		else {
//			viewHolder.funcTitleTv.setVisibility(View.GONE);
//		}

		viewHolder.tvSendTime.setText(info.getDateStr());
		int msgType = info.getContentType();
		Log.debug(getClass(), "getView msgType = " + msgType);

		if(msgType == SessionInfo.ContentType_FileURL)
		{
			viewHolder.textTv.setVisibility(View.GONE);
			String fileMataStr = info.getFileMetaData();
			Log.debug(getClass(), "getView fileMataStr = " + fileMataStr);
			FileMataInfo fileMataInfo = FileMataInfo.parse(fileMataStr);
			String name = fileMataInfo.getFileName();
			String type = fileMataInfo.getType();
			Log.debug(getClass(), "getView name = " + name + " type = " + type);

			if(FileOperation.isPicture(type))
			{

				if (SessionInfo.Direction_Type_Send == direction)
				{
					String localPath = info.getLocalPath();
					Log.debug(getClass(), "getView isPicture  send http localPath = " + localPath);
//					Picasso.with(ctx).load(path).resize(200, 200)
//							.onlyScaleDown().into(viewHolder.imageIv);
//					File file = new File(localPath);
//					Glide.with(ctx)
//							.load(file)
//							.into(viewHolder.imageIv);
					Picasso.get().load("file://" + localPath).fit()          // 自动适配 ImageView 的尺寸
							.centerInside() // 保持宽高比
					 .into(viewHolder.imageIv);
				}
				else
				{
					String path = info.getContent();
					String localPath = info.getLocalPath();
					Log.debug(getClass(), "getView isPicture recv http path = " + path + " localPath = " + localPath);
					if(localPath != null
							&& localPath.equals("")) {
//						Glide.with(ctx)
//								.load(path)
//								.override(200, 200)
//								.diskCacheStrategy(DiskCacheStrategy.ALL)
//								.into(viewHolder.imageIv);
						Picasso.get().load(path).fit().centerInside().into(viewHolder.imageIv);
					}
					else
					{
//						File file = new File(localPath);
//						Glide.with(ctx)
//								.load(file)
//								.into(viewHolder.imageIv);
						Picasso.get().load("file://" + localPath).fit().centerInside().into(viewHolder.imageIv);
					}
				}

				viewHolder.textTv.setVisibility(View.GONE);
				viewHolder.imageIv.setVisibility(View.VISIBLE);
				viewHolder.voiceIv.setVisibility(View.GONE);
				viewHolder.fileLy.setVisibility(View.GONE);
			}
			else if (FileOperation.isAudio(type))
			{
				String path = info.getContent();
				Log.debug(getClass(), "getView isAudio path = " + path);
//				Picasso.with(ctx).load(path).into(viewHolder.voiceIv);
				viewHolder.textTv.setVisibility(View.GONE);
				viewHolder.imageIv.setVisibility(View.GONE);
				viewHolder.voiceIv.setVisibility(View.VISIBLE);
				viewHolder.fileLy.setVisibility(View.GONE);
			}
			else
			{
				String size = fileMataInfo.getSizeStr();
				viewHolder.fileLy.setVisibility(View.VISIBLE);
				viewHolder.fileNameTv.setText(name);
				viewHolder.fileSizeTv.setText(size);

				viewHolder.textTv.setVisibility(View.GONE);
				viewHolder.imageIv.setVisibility(View.GONE);
				viewHolder.voiceIv.setVisibility(View.GONE);
			}
			viewHolder.imageIv.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// 在这里，position就是点击的控件所在的行
					// 你可以在这里处理点击事件，例如弹出Toast或者跳转到另一个Activity
					doViewClick(R.id.imageIv,position);
				}
			});
			viewHolder.voiceIv.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// 在这里，position就是点击的控件所在的行
					// 你可以在这里处理点击事件，例如弹出Toast或者跳转到另一个Activity
					doViewClick(R.id.voiceIv,position);
				}
			});
			viewHolder.fileLy.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// 在这里，position就是点击的控件所在的行
					// 你可以在这里处理点击事件，例如弹出Toast或者跳转到另一个Activity
					doViewClick(R.id.fileLy,position);
				}
			});
		}
		else
		{
			viewHolder.textTv.setVisibility(View.VISIBLE);
			viewHolder.imageIv.setVisibility(View.GONE);
			viewHolder.voiceIv.setVisibility(View.GONE);
			viewHolder.fileLy.setVisibility(View.GONE);
			String content = info.getContent();
			Log.debug(getClass(), "getView content = " + content);
			viewHolder.textTv.setText(content);
		}

		return convertView;
	}


	public void clearSelect(){

	}

	public void doViewClick(int id,int pos) {
		Log.debug(getClass(), "doViewClick id = " + id + " R.id.stateTv = " + R.id.stateTv + " pos = " + pos);
		if(id == R.id.imageIv
				||id == R.id.voiceIv
				|| id == R.id.fileLy)
		{
			SessionInfo info = list.get(pos);
			int msgType = info.getContentType();
			int direction = info.getDirection();
			if (SessionInfo.Direction_Type_Send == direction)
			{
				return;
			}
			if (msgType == SessionInfo.ContentType_FileURL) {
				final String path = info.getContent();
				Log.debug(getClass(), "onClick path = " + path);
				String fileMataStr = info.getFileMetaData();
				Log.debug(getClass(), "getView fileMataStr = " + fileMataStr);
				FileMataInfo fileMataInfo = FileMataInfo.parse(fileMataStr);
				String name = fileMataInfo.getFileName();
				Log.debug(getClass(), "getView name = " + name);

				if (FileOperation.isAudio(name)) {

					AudioPlayer.playSound(ctx, path, null);

				} else {
					String localPath = info.getLocalPath();
					Log.debug(getClass(), "onClick localPath = " + localPath);
					if(localPath != null
							&& localPath.equals(""))
					{
						if(download != null) {
							download.showDownloadDialog(info);
						}
					}
				}
			}
		}
		else if(id == R.id.stateTv)
		{
			SessionInfo info = list.get(pos);
			if(!info.isOtoMsg())
			{
				Intent intent = new Intent();
				intent.setClass(ctx, MessagesStatusActivity.class);
				intent.putExtra(SessionActivity.KEY,info);
				//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				ctx.startActivity(intent);
			}
		}
	}

	private class ViewHolder {
		public ImageView imgView;

		public TextView tvSendTime;
//		public TextView funcTitleTv;

		public TextView tvUserName;
		//		public FrameLayout contentLy;
		public TextView textTv;
		//		public LinearLayout ly_file;
//		public TextView tv_left_len;
		public ImageView voiceIv;
		public ImageView imageIv;
		public LinearLayout fileLy;
		public TextView fileNameTv;
		public TextView fileSizeTv;

		public TextView statusTv;
//		public TextView tv_right_len;
		//		public boolean isComMsg = true;  
	}

}
